import toolApi from '@/config/server/api/tool'
import userApi from '@/config/server/api/user'
import server from '@/config/server'
import store from '@/store'
import axios from 'axios' // 注意先安装哦
import dt from '@dt/dt'
import { Message } from 'view-design'
import tool from '@/common/tool.js'

// 上传图片
function unloadImage(data = {}) {
  data.fileName = 'multipartFile'
  let upload = toolApi.unloadImg()
  upload.setData(data)
  return upload
}

// 上传文件
function unloadFile(data = {}) {
  data.fileName = 'multipartFile'
  let upload = toolApi.unloadFile()
  upload.setData(data)
  return upload
}

// 下载文件到下载中心
function downloadCenter(path, data, method = 'post') {
  let serverMethod =
    method === 'get' ? server.api().get(path).setTimeout(60000) : server.api().post(path).setTimeout(60000)
  return serverMethod
    .fetch(data)
    .then(() => {
      store.dispatch('downloadModelFlag', true)
    })
    .catch((err) => {
      Message.error('生成失败，请重新生成！')
    })
}

// 获取四级组织架构  qryType合成班传：1
// @ApiParam(value = "查询类型：statisticalType
// 默认可不传，不传默认全查询,0全部不查询 1带楼盘数量 2海报数量
// 3段文章数量 4短文章发送数量 5置业笔记数量 6案场“线索分配”任务责任人是否存在  1:存在 2:不存在")
// level  组织架构层级

function getBuildingOrg(data, statisticalType = 0, level = 4) {
  console.log(data, 'ddddddd')
  let params = {
    ...data,
    statisticalType
  }
  return userApi.organ.getBuildingOrg.fetch(params).then((res) => {
    return dealOrganization(res, level)
  })
}
// 根据权限获取组织架构
function organization(level = 3) {
  return userApi.organ.getWebOrg.fetch().then((res) => {
    return dealOrganization(res, level)
  })
}

function dealOrganization(res, level) {
  return res.map((i) => {
    i.label = i.orgName
    i.value = i.orgId
    i.title = i.orgName
    i.id = i.orgId
    if (level - 1 > 0) {
      i.children = dealOrganization(i.children, level - 1)
    } else {
      delete i.children
    }
    return i
  })
}

// 区分ie浏览器和chrome浏览器实现修改文件名
function downloadFile(url, fileName, encode, suffix, noHomologous) {
  let urlPathload = url
  if (encode) {
    const tmpFileName = url.split('/').pop()
    const urlPath = url.split(tmpFileName)[0]
    urlPathload = urlPath + encodeURIComponent(tmpFileName)
    console.log(tmpFileName, urlPath, urlPathload)
  }
  let flagUrl = url.indexOf('tospurfang')
  if (noHomologous && flagUrl < 0) {
    console.log(url, 'noHomologous')
    let link = document.createElement('a')
    link.href = `${url}` // a标签下载同源策略
    link.download = fileName
    link.click()
  } else if (url.indexOf('http://') >= 0) {
    let link = document.createElement('a'),
      href = url.replace('http://', 'https://')
    link.href = `${href}?response-content-type=application/octet-stream` // a标签下载同源策略
    link.download = fileName
    link.click()
  } else {
    console.log(suffix, 'axios')
    axios({
      method: 'get',
      url: encode ? urlPathload : url,
      // data:  encryptList.Encrypt(JSON.stringify(params)),
      // data: params,
      responseType: 'blob'
      // headers: {
      //   'token': tool.getToken(),
      //   appId: 36,
      //   'Content-Type': 'application/x-www-form-urlencoded'
      // }
    })
      .then((res) => {
        const link = document.createElement('a')
        const blob = new Blob([res.data], {
          type: suffix || 'application/vnd.ms-excel'
        })
        link.style.display = 'none'
        link.href = URL.createObjectURL(blob)
        link.setAttribute('download', `${fileName}`)
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
      })
      .catch((err) => {
        console.log('导出报错', err)
      })
  }
}

// 视频类
function getVideoAddressAndAuth(info) {
  return toolApi.getVideoAddressAndAuth.fetch(info)
}

function refreshUploadVideo(info) {
  return toolApi.refreshUploadVideo.fetch(info)
}

function getPlayMess(info) {
  return toolApi.getPlayMess.fetch(info)
}

// 日期范围校验
function checkDate(startDate, endDate, msg, time = 2) {
  if (tool.dateDiff(startDate, endDate).Y >= time) {
    // 日期最大跨度两年
    Message.warning(msg)
  }
  return !(tool.dateDiff(startDate, endDate).Y >= time)
}

export default {
  unloadImage,
  unloadFile,
  downloadCenter,
  organization,
  getBuildingOrg,
  downloadFile,
  getVideoAddressAndAuth,
  refreshUploadVideo,
  getPlayMess,
  checkDate
}
